package cn.bonoon.kernel.menus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cn.bonoon.kernel.menus.privileges.PrivilegeInspector;
import cn.bonoon.kernel.util.StringHelper;


class ChannelDefinitionImpl extends AbstractMenuable implements ChannelDefinition{
	
	protected List<TabsDefinition> tabs;
	
//	/** 在频道上的子菜单的提示信息 */
//	private List<MenuTipHandler> tipHandlers;

	public ChannelDefinitionImpl(){ }
	
	public ChannelDefinitionImpl(int ordinal, String id, String name){
		this.id = id;
		this.name = name;
		this.ordinal = ordinal;
	}
	
	@Override
	protected void init(PlatformContext platformContext, ModuleContext moduleContext, ParentContainer parent){
		
		super.init(platformContext, moduleContext, parent);
		
		//TODO 应该在后面追加定义的tabs的菜单
		if(null == tabs){
			tabs = Collections.emptyList();
		}else{
		
			for(TabsDefinition tab : tabs){
				tab.init(platformContext, moduleContext, this);
				tab.navigation = platformContext.navigateGenerate(this, tab);
				platformContext.add(tab);
			}
			
			Collections.sort(tabs);
		}
	}
	
//	void add(MenuTipHandler handler){
//		if(null == tipHandlers) tipHandlers = new ArrayList<>();
//		tipHandlers.add(handler);
//	}

	@Override
	protected ChannelDefinitionImpl internalChannel() {
		return this;
	}
	
	@Override
	public String navigation() {
		return name;
	}
	
	/** 这里返回的一定不会是null */
	public List<TabsDefinition> getTabs() {
		return tabs;
	}
	
	public void add(TabsDefinition tab){
		if(null == tabs) tabs = new ArrayList<TabsDefinition>();
		
		tabs.add(tab);
	}
	
	@Override
	protected void resolveButtonName(StringBuilder a) {
		a.append("<span>").append(name).append("</span>");
	}
	
	//TODO 使用递归访问所有的子菜单，并找出可以访问的子菜单出来   这里需要修改，在3.1版本中
	private boolean __visit(List<MenuDefinitionImpl> menus, PrivilegeInspector privilege, StringBuilder a){
		if(null == menus) return false;
		
		for(MenuDefinitionImpl mi : menus){
			//找出第一个有权限的子菜单
			if(!privilege.hasPrivilege((MenuDefinition)mi)) continue;
			
			if("javascript:void(null);".equals(mi.href)){
				
				if(__visit(mi.menus, privilege, a)) return true;
				
				continue;
			}
			
			_button(mi.href, a, "");
			return true;
		}
		
		return false;
	}
	
	public void button(PrivilegeInspector privilege, StringBuilder a) {
		if(StringHelper.isNotEmpty(href)){
			_button(href, a, "");
			return;
		}

		if(__visit(menus, privilege, a)) return;
		
		if(null == tabs) return;
		
		//在tabs里查找是否有权限
		for(TabsDefinition ti : tabs){
			if(!privilege.hasPrivilege(ti)) continue;
			
			_button(ti.href, a, "");
			return;
		}
	}
	
}
